package cn.rkylin.oms.sysOrder.service;

import cn.rkylin.apollo.common.util.HttpUtils;
import cn.rkylin.core.utils.SnoGerUtil;
import cn.rkylin.oms.common.dto.DBLog;
import cn.rkylin.oms.common.utils.CodeUtil;
import cn.rkylin.oms.common.utils.LogUtil;
import cn.rkylin.oms.sysOrder.dao.ISysOrderDAO;
import cn.rkylin.oms.sysOrder.domain.SysOrderGoods;
import cn.rkylin.oms.sysOrder.vo.SysOrderVO;
import cn.rkylin.oms.sysrefund.servcie.ISysRefundService;
import cn.rkylin.oms.sysrefund.vo.SysRefundVO;
import cn.rkylin.oms.system.shop.vo.ShopVO;
import cn.rkylin.oms.warehouse.shiporder.domain.ShiporderSku;
import cn.rkylin.oms.warehouse.shiporder.service.IShiporderService;
import cn.rkylin.oms.warehouse.shiporder.vo.ShiporderVO;
import cn.rkylin.oms.warehouseDocking.vo.BatchStockVO;
import cn.rkylin.oms.warehouseDocking.vo.StockVO;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 审核系统订单
 *
 * @author wangxing
 * @version 1.0
 * @created 2017.09.14
 */
@Service("verifySysOrderService")
public class VerifySysOrderService {

    //待审核的系统订单数据集
//    private List<SysOrderVO> sysOrderAllList = null;
    //系统订单商品与系统订单关联关系map
//    private Map<String, List<SysOrderGoods>> sysOrderGoodsMap = null;
    //审核原因类型
//    private String strErrorType = "";

    @Autowired
    private ISysOrderDAO sysOrderDAO;

    /**
     * sysRefundService:系统退款单服务层.
     */
    @Autowired
    private ISysRefundService sysRefundService;

    /**
     * shiporderService:系统发货单服务层.
     */
    @Autowired
    private IShiporderService shiporderService;

    /**
     * OMS调用地址
     */
    @Value("${oms.address}")
    private String omsUrl;

    /**
     * 日志类
     */
    @Autowired
    private LogUtil logUtil;

    /**
     * 审核系统订单
     *
     * @throws Exception
     */
    public void verifySysOrder(ShopVO shopVO) throws Exception {
        //店铺id
        String strShopId = shopVO.getShopId();
        logUtil.info(new DBLog(strShopId, "系统订单自动审核分派", "跟踪日志", "shopAccount:" + shopVO.getShopAccount() + " 系统订单自动审核分派开始---------------------------------------"));
        //项目简称
        String strPrjShortName = shopVO.getPrjShortName();
        //项目昵称
        String strShopAccount = shopVO.getShopAccount();
        //待合并的系统订单数据集
        List<SysOrderVO> sysOrderAllList = new ArrayList<SysOrderVO>();
        //系统订单商品与系统订单关联关系map
        Map<String, List<SysOrderGoods>> sysOrderGoodsMap = new HashMap();

//1.1、获取待审核的系统订单数据集------------------------------------------------------------------------------------------
        logUtil.info(new DBLog(strShopId, "系统订单自动审核分派", "跟踪日志", "获取待审核分派系统订单开始---------------------"));
        Map<String, Object> orderIdAddMap = new HashMap();
        sysOrderAllList = getSysOrderList(strShopId, orderIdAddMap);
        logUtil.info(new DBLog(strShopId, "系统订单自动审核分派", "跟踪日志", "获取待审核分派系统订单结束---------------------"));
        if (sysOrderAllList != null && sysOrderAllList.size() > 0) {
            logUtil.info(new DBLog(strShopId, "系统订单自动审核分派", "跟踪日志", "获取待审核分派系统订单数为:" + String.valueOf(sysOrderAllList.size())));
//1.2、获取系统订单商品数据集，并映射Map关系------------------------------------------------------------------------------------------
            logUtil.info(new DBLog(strShopId, "系统订单自动审核分派", "跟踪日志", "获取待审核分派系统订单商品开始---------------------"));
            sysOrderGoodsMap = getSysOrderGoodsMap(orderIdAddMap, strShopId);
            logUtil.info(new DBLog(strShopId, "系统订单自动审核分派", "跟踪日志", "获取待审核分派系统订单商品结束---------------------"));
//1.3、循环订单校验各种问题单------------------------------------------------------------------------------------------
            //系统订单实体VO
            SysOrderVO sysOrderVO = new SysOrderVO();
            int iRes = 0;
            //审核原因类型
            String strErrorType = "";
            //循环系统订单
            for (int orderIndex = 0; orderIndex < sysOrderAllList.size(); orderIndex++) {
                sysOrderVO = sysOrderAllList.get(orderIndex);
                logUtil.info(new DBLog(strShopId, "系统订单自动审核分派", "跟踪日志", "订单编号" + sysOrderVO.getOrderCode() + "审核开始*******************"));
                iRes = 0;
                strErrorType = "";
////订单审核 begin--------------------------------------------------------------------------
//1.4、清空所有问题单状态(初始化)--------------------------------------------------------------------------------------
                logUtil.info(new DBLog(strShopId, "系统订单自动审核分派", "跟踪日志", "订单编号" + sysOrderVO.getOrderCode() + "清空所有问题单状态开始*******************"));
                updateSysOrderErrorStatus(sysOrderVO.getOrderId(), "", "", 0, strShopId);
                logUtil.info(new DBLog(strShopId, "系统订单自动审核分派", "跟踪日志", "订单编号" + sysOrderVO.getOrderCode() + "清空所有问题单状态结束*******************"));
//1.5、订单问题校验开始--------------------------------------------------------------------------------------
                logUtil.info(new DBLog(strShopId, "系统订单自动审核分派", "跟踪日志", "订单编号" + sysOrderVO.getOrderCode() + "订单问题校验开始*******************"));
                iRes += getOrderError(sysOrderVO, shopVO, strErrorType);
                logUtil.info(new DBLog(strShopId, "系统订单自动审核分派", "跟踪日志", "订单编号" + sysOrderVO.getOrderCode() + "订单问题校验结束*******************"));
//1.6、商品问题校验开始--------------------------------------------------------------------------------------
                logUtil.info(new DBLog(strShopId, "系统订单自动审核分派", "跟踪日志", "订单编号" + sysOrderVO.getOrderCode() + "商品问题校验开始*******************"));
                iRes += getOrderSkuError(sysOrderVO, sysOrderGoodsMap, strErrorType);
                logUtil.info(new DBLog(strShopId, "系统订单自动审核分派", "跟踪日志", "订单编号" + sysOrderVO.getOrderCode() + "商品问题校验结束*******************"));
//1.7、物流问题校验开始--------------------------------------------------------------------------------------
                logUtil.info(new DBLog(strShopId, "系统订单自动审核分派", "跟踪日志", "订单编号" + sysOrderVO.getOrderCode() + "物流问题校验开始*******************"));
                iRes += getLgstError(sysOrderVO, strErrorType);
                logUtil.info(new DBLog(strShopId, "系统订单自动审核分派", "跟踪日志", "订单编号" + sysOrderVO.getOrderCode() + "物流问题校验结束*******************"));
//1.8、库存问题校验开始--------------------------------------------------------------------------------------
                logUtil.info(new DBLog(strShopId, "系统订单自动审核分派", "跟踪日志", "订单编号" + sysOrderVO.getOrderCode() + "库存问题校验开始*******************"));
                iRes += getStockError(sysOrderVO, shopVO, sysOrderGoodsMap, strErrorType);
                logUtil.info(new DBLog(strShopId, "系统订单自动审核分派", "跟踪日志", "订单编号" + sysOrderVO.getOrderCode() + "库存问题校验结束*******************"));
////订单审核 end----------------------------------------------------------------------------
                if (iRes > 0) {
                    //审核失败，记录日志 （系统自动审核失败：订单问题 商品问题。。。。） + strErrorType
                    logUtil.info(new DBLog(sysOrderVO.getOrderCode(), "系统自动审核", "", "系统自动审核失败：" + strErrorType));
                } else {
//1.9、审核成功，更新审核状态--------------------------------------------------------------------------------------
                    //审核成功，更新订单已审核状态
                    iRes = updateSysOrderErrorStatus(sysOrderVO.getOrderId(), "", "", 10, strShopId);
                    if (iRes > 0) {
                        logUtil.info(new DBLog(sysOrderVO.getOrderCode(), "系统自动审核", "", "系统自动审核成功"));
                        logUtil.info(new DBLog(strShopId, "系统订单自动审核分派", "跟踪日志", "订单编号" + sysOrderVO.getOrderCode() + "审核结束*******************"));
////订单分派 begin--------------------------------------------------------------------------
//2.0、分派开始--------------------------------------------------------------------------------------
                        logUtil.info(new DBLog(strShopId, "系统订单自动审核分派", "跟踪日志", "订单编号" + sysOrderVO.getOrderCode() + "分派开始*******************"));
                        //校验订单商品是否全部都是虚拟商品
                        int iVirt = checkVirt(sysOrderVO.getOrderId(), sysOrderGoodsMap);
                        if (iVirt == -1) {
                            //订单不存在商品明细
                            logUtil.info(new DBLog(sysOrderVO.getOrderCode(), "系统自动分派", "", "系统自动分派失败,订单没有商品明细"));
                        } else if (iVirt == 0) {
//2.1、商品明细全部为虚拟商品，分派失败,打成手动状态-----------------------------------------------------------------------------------
                            //商品明细全部都为虚拟商品，分派失败，不能生成发货单
                            iRes = updateSysOrderErrorStatus(sysOrderVO.getOrderId(), "", "", 12, strShopId);
                            logUtil.info(new DBLog(sysOrderVO.getOrderCode(), "系统自动分派", "", "系统自动分派失败,虚拟商品不生成发货单,订单打成手动状态"));
                        } else {
                            //判断是否存在未取消的发货单；有，则不能生产发货单
                            ShiporderVO shiporderVOOrder = new ShiporderVO();
                            shiporderVOOrder.setSourceId(sysOrderVO.getOrderId());
                            shiporderVOOrder.setCancelStatus("w");
                            ShiporderVO ShiporderVORes = shiporderService.getShiporderInfo(shiporderVOOrder);
                            if (ShiporderVORes == null) {
                                //给发货单实体赋值
                                ShiporderVO shiporderVO = setShiporderInfo(sysOrderVO, strPrjShortName, strShopAccount, sysOrderGoodsMap, strShopId);
                                logUtil.info(new DBLog(strShopId, "系统订单自动审核分派", "跟踪日志", "订单编号" + sysOrderVO.getOrderCode() + "生产发货单赋值阶段结束*******************"));
//2.2、开始对发货单插入到数据库,并更新商品已分派数-----------------------------------------------------------------------------------
                                iRes = insertShiporderInfo(shiporderVO);
                                logUtil.info(new DBLog(strShopId, "系统订单自动审核分派", "跟踪日志", "订单编号" + sysOrderVO.getOrderCode() + "发货单插入数据库阶段结束*******************"));
                                if (iRes > 0) {
//2.3、分派成功，更新分派状态--------------------------------------------------------------------------------------
                                    //分派成功，更新订单已分派状态
                                    iRes = updateSysOrderErrorStatus(sysOrderVO.getOrderId(), "", "", 11, strShopId);
                                    logUtil.info(new DBLog(strShopId, "系统订单自动审核分派", "跟踪日志", "订单编号" + sysOrderVO.getOrderCode() + "分派完成更新订单已分派阶段结束*******************"));
                                    if (iRes > 0) {
                                        logUtil.info(new DBLog(sysOrderVO.getOrderCode(), "系统自动分派", "", "系统自动分派成功"));
                                    }
                                }
                            }
                        }
                    }
////订单分派 end----------------------------------------------------------------------------
                }
            }
        } else {
            logUtil.info(new DBLog(strShopId, "系统订单自动审核分派", "跟踪日志", "获取待审核分派系统订单数为:0"));
        }
        logUtil.info(new DBLog(strShopId, "系统订单自动审核分派", "跟踪日志", "shopAccount:" + shopVO.getShopAccount() + " 系统订单自动审核分派结束---------------------------------------"));
    }

    /**
     * 获取待审核的系统订单数据集，并返回订单id累加数据集Map
     *
     * @param strShopId
     * @return
     * @throws Exception
     */
    private List<SysOrderVO> getSysOrderList(String strShopId, Map<String, Object> orderIdAddMap) throws Exception {
        List<SysOrderVO> sysOrderAllList = new ArrayList<SysOrderVO>();
        try {
            //数据库参数
            Map<String, String> sysOrderMap = new HashMap();
            sysOrderMap.put("shopId", strShopId);
            sysOrderMap.put("orderStatus", "a");
            sysOrderMap.put("jobStep", "p");
            sysOrderMap.put("combStus", "w");
            sysOrderMap.put("isCancel", "n");
            sysOrderMap.put("isLock", "n");
            sysOrderMap.put("operStus", "au");
            sysOrderMap.put("buyerNick", "w");
            sysOrderMap.put("createTimes", "w");//订单进系统5分钟后条件
            sysOrderMap.put("orderBy", "paid_date");//排序 付款日期正序
            //获取待审核的系统订单数据集------------------------------------------------------------------------------------------
            sysOrderAllList = sysOrderDAO.selectSysOrderList(sysOrderMap);
            if (sysOrderAllList != null && sysOrderAllList.size() > 0) {
                //系统订单Id累加拼串，用于获取订单商品信息入参
                List<String> orderIdAddList = new ArrayList<String>();
                for (int orderIndex = 0; orderIndex < sysOrderAllList.size(); orderIndex++) {
                    orderIdAddList.add(sysOrderAllList.get(orderIndex).getOrderId());
                }

                orderIdAddMap.put("order_id", orderIdAddList);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            sysOrderAllList = null;
            orderIdAddMap = null;
            logUtil.error(new DBLog(strShopId, "系统订单自动审核分派", "跟踪日志", "获取待审核分派系统订单异常:" + ex.getMessage()));
        }

        return sysOrderAllList;
    }

    /**
     * 获取系统订单商品数据集，并映射其与系统订单的Map关系
     *
     * @param map
     * @param strShopId
     * @return
     * @throws Exception
     */
    private Map<String, List<SysOrderGoods>> getSysOrderGoodsMap(Map<String, Object> map, String strShopId) throws Exception {
        Map<String, List<SysOrderGoods>> sysOrderGoodsMap = new HashMap();
        try {
            if (map != null && map.size() > 0) {
                //获取系统订单商品数据集------------------------------------------------------------------------------------------
                List<SysOrderGoods> sysOrderGoodsAllList = sysOrderDAO.selectSysOrderGoodsList(map);
                if (sysOrderGoodsAllList != null && sysOrderGoodsAllList.size() > 0) {
                    //系统订单商品实体
                    SysOrderGoods sysOrderGoods = new SysOrderGoods();
                    //系统订单id累加，作为主键
                    String strKey = "";
                    //系统订单商品临时列表
                    List<SysOrderGoods> sysOrderGoodsList = new ArrayList<SysOrderGoods>();
                    //循环系统订单 按合并订单条件各自组合Map
                    for (int orderGoodsIndex = 0; orderGoodsIndex < sysOrderGoodsAllList.size(); orderGoodsIndex++) {
                        sysOrderGoods = sysOrderGoodsAllList.get(orderGoodsIndex);
                        strKey = sysOrderGoods.getOrderId();
                        if (sysOrderGoodsMap.get(strKey) != null) {
                            sysOrderGoodsList = sysOrderGoodsMap.get(strKey);
                        } else {
                            sysOrderGoodsList = new ArrayList<SysOrderGoods>();
                        }
                        //累加系统订单商品
                        sysOrderGoodsList.add(sysOrderGoods);
                        sysOrderGoodsMap.put(strKey, sysOrderGoodsList);
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            sysOrderGoodsMap = null;
            logUtil.error(new DBLog(strShopId, "系统订单自动审核分派", "跟踪日志", "获取待审核分派系统订单商品异常:" + ex.getMessage()));
        }

        return sysOrderGoodsMap;
    }

    /**
     * 订单问题，逻辑校验处理
     * 1、存在可合并、已审核未完成、不可操作的系统订单 (二期暂时不做)
     * 2、存在可合并但有未废弃退款单的订单(排除自身) (二期暂时不做)
     * 3、有买家留言
     * 4、有卖家备注
     * 5、收货地址超长
     * 6、存在未废弃的退款单
     * 7、订单状态与平台状态不一致
     * 8、合并订单数量大于15
     * 9、收货人或手机、电话信息为空
     *
     * @param sysOrder
     * @param shopVO
     * @return
     * @throws Exception
     */
    private int getOrderError(SysOrderVO sysOrder, ShopVO shopVO, String strErrorType) throws Exception {
        int iRes = 0;
        //已验视的订单，跳过当前问题单校验，按通过处理
        if (StringUtils.isNotBlank(sysOrder.getHasInspected())
                && "y".equals(sysOrder.getHasInspected())) {
            return 0;
        }
        String strErrorRemark = "";//问题原因
//1、订单问题单：存在可合并、已审核未完成、不可操作的系统订单 (二期暂时不做)--------------------------------------------------------------
       /* if ("y".equals(shopVO.getHasErrorOrderR1())) {
            //开关开启
            iRes += getOrderError_E1(sysOrder, shopVO.getShopId());//二期暂时不做
        }*/
//2、订单问题单：存在可合并但有未废弃退款单的订单(排除自身) (二期暂时不做)--------------------------------------------------------------
        /*if ("y".equals(shopVO.getHasErrorOrderR2())) {
            //开关开启
            //预留未实现///////////////////////////////////////////////////////////
        }*/
//3、订单问题单：有买家留言 -----------------------------------------------------------------------------------------
        if ("y".equals(shopVO.getHasCustRemark()) && StringUtils.isNotBlank(sysOrder.getCustRemark())) {
            //开关开启，有买家留言
            strErrorRemark = strErrorRemark + " 有买家留言";
        }
//4、订单问题单：有卖家备注 -----------------------------------------------------------------------------------------
        if ("y".equals(shopVO.getHasSalesRemark()) && StringUtils.isNotBlank(sysOrder.getSalesRemark())) {
            //开关开启，有卖家备注
            strErrorRemark = strErrorRemark + " 有卖家备注";
        }
//5、订单问题单：收货地址超长 -----------------------------------------------------------------------------------------
        if (shopVO.getOrderConsAddrLen() > 0 && sysOrder.getConsAddrLength() > shopVO.getOrderConsAddrLen()) {
            //开关开启，收货地址超长
            strErrorRemark = strErrorRemark + " 订单收货地址超过" + String.valueOf(shopVO.getOrderConsAddrLen()) + "字节";
        }
//6、订单问题单：存在未废弃的退款单 -----------------------------------------------------------------------------------------
        //调用系统退款单Service获取系统退款单
        SysRefundVO sysRefundVO = new SysRefundVO();
        sysRefundVO.setOrderId(sysOrder.getOrderId());
        sysRefundVO.setIsCancel("n");
        List<SysRefundVO> sysRefundVOList = sysRefundService.getSysRefundListByCondition(sysRefundVO);
        if (sysRefundVOList != null && sysRefundVOList.size() > 0) {
            //存在未废弃的退款单
            strErrorRemark = strErrorRemark + " 存在未废弃的退款单";
        }
//7、订单问题单：订单状态与平台状态不一致 -----------------------------------------------------------------------------------------
        if (StringUtils.isNotBlank(sysOrder.getTradeStatus())
                && !"EC_WAIT_SELLER_SEND".equals(sysOrder.getTradeStatus())
                && !"EC_WAIT_BUYER_PAY".equals(sysOrder.getTradeStatus())) {
            //平台状态不是等待卖家发货和未付款
            strErrorRemark = strErrorRemark + " 订单状态与平台状态不一致";
        }
//8、订单问题单：合并订单数量大于15 -----------------------------------------------------------------------------------------
        if (StringUtils.isNotBlank(sysOrder.getTradeCode())
                && StringUtils.isNotBlank(sysOrder.getCombStus())
                && "c".equals(sysOrder.getCombStus())) {
            String[] strTradeCodeArry = sysOrder.getTradeCode().split(",");
            if (strTradeCodeArry.length > 15) {
                //平台交易号拼串长度大于15
                strErrorRemark = strErrorRemark + " 合并后订单的子订单数目大于15条";
            }
        }
//9、订单问题单：收货人或手机、电话信息为空 -----------------------------------------------------------------------------------------
        if (StringUtils.isBlank(sysOrder.getCons())
                || (StringUtils.isBlank(sysOrder.getConsMobile())
                && StringUtils.isBlank(sysOrder.getConsTel()))) {
            //收货人或手机、电话信息为空
            strErrorRemark = strErrorRemark + " 收货人或手机、电话信息为空";
        }
        //更新问题单标识及备注
        if (StringUtils.isNotBlank(strErrorRemark)) {
            iRes = updateSysOrderErrorStatus(sysOrder.getOrderId(), sysOrder.getOrderErrorRemark(), strErrorRemark, 1, shopVO.getShopId());
        }
        if (iRes > 0) {
            strErrorType = strErrorType + " 订单问题";
        }
        return iRes;
    }

    /**
     * 订单问题单：存在可合并、已审核未完成、不可操作的系统订单（二期暂不做）
     *
     * @param sysOrder
     * @param strShopId
     * @return
     * @throws Exception
     */
    private int getOrderError_E1(SysOrderVO sysOrder, String strShopId) throws Exception {
        int iRes = 0;
        Map<String, String> sysOrderMap = new HashMap();
        sysOrderMap.put("shopId", strShopId);
        sysOrderMap.put("buyerNick", sysOrder.getBuyerNick());
        sysOrderMap.put("cons", sysOrder.getCons());
        sysOrderMap.put("consAddr", sysOrder.getConsAddr());
        sysOrderMap.put("orderStatus", "w");
        sysOrderMap.put("combStus", "w");
        sysOrderMap.put("isCancel", "n");
        sysOrderMap.put("isLock", "n");
        sysOrderMap.put("tradeStatus", "w");//平台状态不是'EC_TRADE_ALL_SEND','WAIT_BUYER_CONFIRM_GOODS','WAIT_GOODS_RECEIVE_CONFIRM'
        sysOrderMap.put("orderSku", "gift");//订单存在非赠品的商品明细
        //获取与当前订单 可合并、已审核未完成、不可操作的系统订单数据集------------------------------------------------------------------------------------------
        List<SysOrderVO> sysOrderExtList = sysOrderDAO.selectSysOrderList(sysOrderMap);
        if (sysOrderExtList != null && sysOrderExtList.size() > 0) {
            //系统订单Id累加拼串，用于获取发货单信息入参
            List<String> orderIdAddList = new ArrayList<String>();
            for (int sysOrderIndex = 0; sysOrderIndex < sysOrderExtList.size(); sysOrderIndex++) {
                orderIdAddList.add(sysOrderExtList.get(sysOrderIndex).getOrderId());
            }
            Map<String, Object> returnMap = new HashMap();
            returnMap.put("order_id", orderIdAddList);
            //此处缺少过滤掉存在系统退款单的订单处理(别的地方有，可以拿过来用)////////////////////////////////////
//  调用OMS发货单Controller 判断上面的订单是否存在未取消、已被拿走的发货单 入参为： 过滤掉存在退款单的订单id
            Map<String, String> sysOrderShipMap = new HashMap();//返回的发货单结果集/////////////////
            if (sysOrderShipMap.size() > 0) {
                //订单问题备注：存在以下已审核但仍可合并的订单，建议将其合并后一起发货：+ OrderCode拼串
                SysOrderVO sysOrderVO = new SysOrderVO();
                sysOrderVO.setOrderId(sysOrder.getOrderId());
                sysOrderVO.setOperStus("pr");
                sysOrderVO.setIsOrderError("y");
                sysOrderVO.setOrderErrorRemark(sysOrder.getOrderErrorRemark() + " 存在以下已审核但仍可合并的订单，建议将其合并后一起发货：");
                iRes = sysOrderDAO.updateByPrimaryKeySelectiveSysOrder(sysOrderVO);
            }
        }
        return iRes;
    }

    /**
     * 商品问题，逻辑校验处理(无商品明细或者系统商品未关联)
     *
     * @param sysOrder
     * @return
     * @throws Exception
     */
    private int getOrderSkuError(SysOrderVO sysOrder, Map<String, List<SysOrderGoods>> sysOrderGoodsMap, String strErrorType) throws Exception {
        int iRes = 0;
        String strErrorRemark = "";//问题原因
        //判断订单商品明细是否存在，不存在直接打成商品问题单
        if (sysOrderGoodsMap != null && sysOrderGoodsMap.size() > 0) {
            List<SysOrderGoods> sysOrderGoodsList = sysOrderGoodsMap.get(sysOrder.getOrderId());
            if (sysOrderGoodsList != null && sysOrderGoodsList.size() > 0) {
                int iError = 0;
                for (SysOrderGoods sysOrderGoods : sysOrderGoodsList) {
                    //判断订单商品明细中是否存在非赠品
                    if ("n".equals(sysOrderGoods.getIsGift())) {
                        iError = 1;
                        break;
                    }
                }
                //不存在非赠品的商品明细，打成商品问题单
                if (iError == 0) {
                    strErrorRemark = strErrorRemark + " 无商品明细或者系统商品未关联";
                } else {
                    //判断商品明细中是否存在未关联系统商品的
                    for (SysOrderGoods sysOrderGoods : sysOrderGoodsList) {
                        //判断订单商品明细中是否存在非赠品
                        if (StringUtils.isBlank(sysOrderGoods.getSkuId())) {
                            iError = 0;
                            break;
                        }
                    }
                    //存在未关联系统商品的订单商品明细，打成商品问题单
                    if (iError == 0) {
                        strErrorRemark = strErrorRemark + " 无商品明细或者系统商品未关联";
                    }
                }
            } else {
                strErrorRemark = strErrorRemark + " 无商品明细或者系统商品未关联";
            }
        } else {
            strErrorRemark = strErrorRemark + " 无商品明细或者系统商品未关联";
        }
        //更新问题单标识及备注
        if (StringUtils.isNotBlank(strErrorRemark)) {
            iRes = updateSysOrderErrorStatus(sysOrder.getOrderId(), sysOrder.getGoodsErrorRemark(), strErrorRemark, 2, sysOrder.getShopId());
        }
        if (iRes > 0) {
            strErrorType = strErrorType + " 商品问题";
        }
        return iRes;
    }

    /**
     * 物流问题，逻辑校验处理
     * 1、快递不到或者没有指定库房、物流公司
     * 2、收货地址信息不明确(台湾) ， 前两字是 ‘台湾’ 第三个字不是 ‘省’
     *
     * @param sysOrder
     * @return
     * @throws Exception
     */
    private int getLgstError(SysOrderVO sysOrder, String strErrorType) throws Exception {
        int iRes = 0;
        //已验视的订单，跳过当前问题单校验，按通过处理
        if (StringUtils.isNotBlank(sysOrder.getHasInspected())
                && "y".equals(sysOrder.getHasInspected())) {
            return 0;
        }
        String strErrorRemark = "";//问题原因

        //1、仓库为空 或 物流公司为空 或 地区码为0  (仓库为空的物流问题改到库存问题里去了。。。。。。。。。)
        if (StringUtils.isBlank(sysOrder.getLgstId())
                || sysOrder.getAreaCoding() == 0) {
//            strErrorRemark = strErrorRemark + " 快递不到或者没有指定库房、物流公司";
            strErrorRemark = strErrorRemark + " 快递不到或者没有指定物流公司";
        }
        //2、收货地址信息不明确(台湾) 前两字是 ‘台湾’ 第三个字不是 ‘省’
        if (StringUtils.isNotBlank(sysOrder.getConsAddr())
                && sysOrder.getConsAddr().length() > 2
                && "台湾".equals(sysOrder.getConsAddr().substring(0, 2))
                && !"省".equals(sysOrder.getConsAddr().substring(2, 1))) {
            strErrorRemark = strErrorRemark + " 收货地址信息不明确(台湾)";
        }
        //更新问题单标识及备注
        if (StringUtils.isNotBlank(strErrorRemark)) {
            iRes = updateSysOrderErrorStatus(sysOrder.getOrderId(), sysOrder.getLgstErrorRemark(), strErrorRemark, 3, sysOrder.getShopId());
        }
        if (iRes > 0) {
            strErrorType = strErrorType + " 物流问题";
        }
        return iRes;
    }

    /**
     * 库存问题，逻辑校验处理(商品订购数大于仓库可分派数)
     *
     * @param sysOrder
     * @param shopVO
     * @return
     * @throws Exception
     */
    private int getStockError(SysOrderVO sysOrder, ShopVO shopVO, Map<String, List<SysOrderGoods>> sysOrderGoodsMap, String strErrorType) throws Exception {
        int iRes = 0;
        String strErrorRemark = "";//问题原因

        //开关开启，仓库为空，直接打成库存问题
        if ("y".equals(shopVO.getIsCheckCanallotqty()) && StringUtils.isBlank(sysOrder.getStorId())) {
            strErrorRemark = "没有指定仓库";
            //更新问题单标识及备注
            if (StringUtils.isNotBlank(strErrorRemark)) {
                iRes = updateSysOrderErrorStatus(sysOrder.getOrderId(), sysOrder.getStockErrorRemark(), strErrorRemark, 4, shopVO.getShopId());
            }
            if (iRes > 0) {
                strErrorType = strErrorType + " 库存问题";
            }
            return 1;
        }

        //开关开启，仓库不为空
        if ("y".equals(shopVO.getIsCheckCanallotqty()) && StringUtils.isNotBlank(sysOrder.getStorId())) {
            // 请求地址
            String requestUrl = omsUrl + "stock/getCanallotQty.action";
            // 请求参数拼接
            String requestParams = "";
            // 请求数据
            String resJson = "";
            // 转换响应数据
            Map<String, Object> resultMap = null;
            String strEntId = sysOrder.getEntId();
            String strStorId = sysOrder.getStorId();
            String strPrjId = sysOrder.getPrjId();
            //获取当前订单商品明细
            List<SysOrderGoods> sysOrderSkuList = sysOrderGoodsMap.get(sysOrder.getOrderId());
            SysOrderGoods sysOrderGoods = new SysOrderGoods();
            List<String> strSkuIdList = new ArrayList<String>();
            int iQty = 0;
            String strSkuId = "";
            //循环当前订单商品明细
            for (int orderSkuIndex = 0; orderSkuIndex < sysOrderSkuList.size(); orderSkuIndex++) {
                sysOrderGoods = sysOrderSkuList.get(orderSkuIndex);
                if (strSkuIdList.contains(sysOrderGoods.getSkuId())) {
                    continue;
                }
                strSkuIdList.add(sysOrderGoods.getSkuId());
                iQty = sysOrderGoods.getQty();
                strSkuId = sysOrderGoods.getSkuId();
                int iCanAllotQty = 0;//调用OMS 仓库模块Controllor,返回当前订单下当前商品的可分派数
                //过滤掉虚拟商品和未匹配系统商品的数据
                if (StringUtils.isNotBlank(sysOrderGoods.getSkuId()) && StringUtils.isNotBlank(sysOrderGoods.getIsVirt())
                        && "n".equals(sysOrderGoods.getIsVirt())) {
                    //再次循环商品明细累加相同系统规格的商品的订购数
                    for (int orderSkuSubIndex = 0; orderSkuSubIndex < sysOrderSkuList.size(); orderSkuSubIndex++) {
                        //排除自己
                        if (orderSkuSubIndex == orderSkuIndex) {
                            continue;
                        }
                        //如果存在相同SkuId的商品明细，订购数累加
                        if (strSkuId.equals(sysOrderSkuList.get(orderSkuSubIndex).getSkuId())) {
                            iQty += sysOrderSkuList.get(orderSkuSubIndex).getQty();
                        }
                    }
//调用OMS 仓库库存模块Controllor,返回当前订单下商品的可分派数 。入参：strEntId,strStorId,strPrjId,strSkuId
                    try {
                        // 请求参数拼接
                        requestParams = "entId=" + strEntId + "&prjId=" + strPrjId + "&skuId=" + strSkuId + "&storId=" + strStorId;
                        // 请求数据
                        resJson = HttpUtils.sendByGet(requestUrl, requestParams);
                        // 转换响应数据
                        resultMap = JSON.parseObject(resJson, Map.class);
                    } catch (Exception ex) {
                        ex.printStackTrace();
                        resultMap = null;
                    }
                    if (resultMap != null && resultMap.size() > 0) {
                        if (resultMap.containsKey("result")
                                && "success".equals(resultMap.get("result"))
                                && resultMap.containsKey("canallotQty")) {
                            String strCanallotQty = resultMap.get("canallotQty").toString();
                            iCanAllotQty = Integer.parseInt(strCanallotQty);
                        } else {
                            //库存问题
                            strErrorRemark = strErrorRemark + " 商品订购数大于仓库可分派数";
                            break;
                        }
                    } else {
                        //库存问题
                        strErrorRemark = strErrorRemark + " 商品订购数大于仓库可分派数";
                        break;
                    }
                    if (iQty > iCanAllotQty) {
                        strErrorRemark = strErrorRemark + " 商品订购数大于仓库可分派数";
                        break;
                    }
                }
            }
            //更新问题单标识及备注
            if (StringUtils.isNotBlank(strErrorRemark)) {
                iRes = updateSysOrderErrorStatus(sysOrder.getOrderId(), sysOrder.getStockErrorRemark(), strErrorRemark, 4, shopVO.getShopId());
            }
            if (iRes > 0) {
                strErrorType = strErrorType + " 库存问题";
            }
        }
        return iRes;
    }


    /**
     * 更新系统订单 问题单状态
     *
     * @param strOrderId
     * @param strOldErrorRemark
     * @param strNewErrorRemark
     * @param iBs               0:清空所有问题单状态(初始化);1:订单问题;2:商品问题;3:物流问题;4:库存问题;10:更新订单审核状态;
     * @return
     * @throws Exception
     */
    private int updateSysOrderErrorStatus(String strOrderId,
                                          String strOldErrorRemark,
                                          String strNewErrorRemark,
                                          int iBs,
                                          String strShopId) throws Exception {
        int iRes = 0;
        try {
            SysOrderVO sysOrderVO = new SysOrderVO();
            sysOrderVO.setOrderId(strOrderId);
            if (iBs == 0) {
                //清空所有问题单状态(初始化)
                sysOrderVO.setIsOrderError("n");
                sysOrderVO.setIsGoodsError("n");
                sysOrderVO.setIsLgstError("n");
                sysOrderVO.setIsStockError("n");
                sysOrderVO.setOrderErrorRemark("");
                sysOrderVO.setGoodsErrorRemark("");
                sysOrderVO.setLgstErrorRemark("");
                sysOrderVO.setStockErrorRemark("");
            } else if (iBs == 1) {
                //订单问题：更新订单标识及备注
                sysOrderVO.setOperStus("pr");
                sysOrderVO.setIsOrderError("y");
                sysOrderVO.setOrderErrorRemark(strNewErrorRemark);
            } else if (iBs == 2) {
                //商品问题：更新订单标识及备注
                sysOrderVO.setOperStus("pr");
                sysOrderVO.setIsGoodsError("y");
                sysOrderVO.setGoodsErrorRemark(strNewErrorRemark);
            } else if (iBs == 3) {
                //物流问题：更新订单标识及备注
                sysOrderVO.setOperStus("pr");
                sysOrderVO.setIsLgstError("y");
                sysOrderVO.setLgstErrorRemark(strNewErrorRemark);
            } else if (iBs == 4) {
                //库存问题：更新订单标识及备注
                sysOrderVO.setOperStus("pr");
                sysOrderVO.setIsStockError("y");
                sysOrderVO.setStockErrorRemark(strNewErrorRemark);
            } else if (iBs == 10) {
                //更新审核成功状态：i
                sysOrderVO.setOrderStatus("i");
            } else if (iBs == 11) {
                //更新分派成功状态：k
                sysOrderVO.setOrderStatus("k");
//            sysOrderVO.setOperStus("al");
            } else if (iBs == 12) {
                //更新操作状态为手动：ma
                sysOrderVO.setOperStus("ma");
            }
            iRes = sysOrderDAO.updateByPrimaryKeySelectiveSysOrder(sysOrderVO);
        } catch (Exception ex) {
            ex.printStackTrace();
            iRes = 0;
            logUtil.error(new DBLog(strShopId, "系统订单自动审核分派", "跟踪日志", "更新系统订单状态异常:" + ex.getMessage()));
        }
        return iRes;
    }


    /**
     * 给发货单实体赋值
     *
     * @param sysOrderVO      系统订单实体
     * @param strPrjShortName 项目简称，用于生成发货单号
     * @return
     * @throws Exception
     */
    private ShiporderVO setShiporderInfo(SysOrderVO sysOrderVO, String strPrjShortName, String strShopAccount,
                                         Map<String, List<SysOrderGoods>> sysOrderGoodsMap, String strShopId) throws Exception {
        //发货单实体
        ShiporderVO shiporderVO = new ShiporderVO();
        try {
            //发货单Id
            String strShiporderId = SnoGerUtil.getUUID();
            shiporderVO.setShiporderId(strShiporderId);
            shiporderVO.setShiporderCode("SO" + strPrjShortName + CodeUtil.getCode());
            shiporderVO.setTradeCode(sysOrderVO.getTradeCode());
            shiporderVO.setSourceId(sysOrderVO.getOrderId());
            shiporderVO.setSourceCode(sysOrderVO.getOrderCode());
            shiporderVO.setSourceType("or");
            shiporderVO.setEntId(sysOrderVO.getEntId());
            shiporderVO.setPrjId(sysOrderVO.getPrjId());
            shiporderVO.setShopId(sysOrderVO.getShopId());
            shiporderVO.setShopName(sysOrderVO.getShopName());
            shiporderVO.setShopAccount(strShopAccount);
            shiporderVO.setStorId(sysOrderVO.getStorId());
            shiporderVO.setStorCode(sysOrderVO.getStorCode());
            shiporderVO.setStorName(sysOrderVO.getStorName());
            shiporderVO.setLgstId(sysOrderVO.getLgstId());
            shiporderVO.setLgstCode(sysOrderVO.getLgstCode());
            shiporderVO.setLgstName(sysOrderVO.getLgstName());
            shiporderVO.setLgstNo(sysOrderVO.getLgstNo());
            shiporderVO.setSourcePlatformCode(sysOrderVO.getShopType());
            shiporderVO.setOrderTime(sysOrderVO.getOrderTime());
            shiporderVO.setProvName(sysOrderVO.getProvName());
            shiporderVO.setCityName(sysOrderVO.getCityName());
            shiporderVO.setDistName(sysOrderVO.getDistName());
            shiporderVO.setAreaCoding(sysOrderVO.getAreaCoding());
            shiporderVO.setCustRemark(sysOrderVO.getCustRemark());
            shiporderVO.setSalesRemark(sysOrderVO.getSalesRemark());
            shiporderVO.setRemark(sysOrderVO.getRemark());
            shiporderVO.setCons(sysOrderVO.getCons());
            shiporderVO.setConsTel(sysOrderVO.getConsTel());
            shiporderVO.setConsMobile(sysOrderVO.getConsMobile());
            shiporderVO.setConsAddr(sysOrderVO.getConsAddr());
            shiporderVO.setBuyerNick(sysOrderVO.getBuyerNick());
            shiporderVO.setPaidDate(sysOrderVO.getPaidDate());
            shiporderVO.setOrderType(sysOrderVO.getOrderType());
            shiporderVO.setPaidFee(sysOrderVO.getPaidFee());
            //获取对应系统订单商品信息列表
            List<SysOrderGoods> sysOrderGoodsList = sysOrderGoodsMap.get(sysOrderVO.getOrderId());
            SysOrderGoods sysOrderGoods = new SysOrderGoods();
            List<ShiporderSku> shiporderSkuList = new ArrayList<ShiporderSku>();

            for (int orderSkuIndex = 0; orderSkuIndex < sysOrderGoodsList.size(); orderSkuIndex++) {
                ShiporderSku shiporderSku = new ShiporderSku();
                sysOrderGoods = sysOrderGoodsList.get(orderSkuIndex);
                //只有非虚拟商品才能生成发货单明细
                if ("n".equals(sysOrderGoods.getIsVirt())) {
                    shiporderSku.setShiporderSkuId(SnoGerUtil.getUUID());
                    shiporderSku.setShiporderId(strShiporderId);
                    shiporderSku.setOrderSkuId(sysOrderGoods.getOrderGoodsId());
                    shiporderSku.setOid(sysOrderGoods.getOid());
                    shiporderSku.setSkuId(sysOrderGoods.getSkuId());
                    shiporderSku.setSkuCode(sysOrderGoods.getSkuCode());
                    shiporderSku.setSkuName(sysOrderGoods.getSkuName());
                    shiporderSku.setGoodsId(sysOrderGoods.getGoodsId());
                    shiporderSku.setGoodsCode(sysOrderGoods.getGoodsCode());
                    shiporderSku.setGoodsName(sysOrderGoods.getGoodsName());
                    shiporderSku.setDivideGoodsFee(sysOrderGoods.getDivideOrderFee()
                            .divide(BigDecimal.valueOf(sysOrderGoods.getQty()), 2, BigDecimal.ROUND_HALF_UP));
                    shiporderSku.setQty(sysOrderGoods.getQty());
                    shiporderSku.setTradeCode(sysOrderGoods.getTradeCode());
                    shiporderSkuList.add(shiporderSku);
                }
            }
            shiporderVO.setShiporderSkuList(shiporderSkuList);

        } catch (Exception ex) {
            ex.printStackTrace();
            shiporderVO = null;
            logUtil.error(new DBLog(strShopId, "系统订单自动审核分派", "跟踪日志", "订单编号" + sysOrderVO.getOrderCode() + "生成系统发货单赋值阶段异常:" + ex.getMessage()));
        }
        return shiporderVO;
    }

    /**
     * 系统发货单插入数据库
     *
     * @param shiporderVO
     * @return
     * @throws Exception
     */
    private int insertShiporderInfo(ShiporderVO shiporderVO) throws Exception {
        int iRes = 0;
        try {
            if (shiporderVO != null) {
                //系统发货单主表信息插入数据库
                iRes = shiporderService.insertSelectiveShiporder(shiporderVO);
                if (iRes > 0) {
                    logUtil.info(new DBLog(shiporderVO.getShiporderCode(), "系统自动分派生成发货单", "系统自动分派生成发货单", "系统自动生成发货单"));
                    int iResSku = 0;
                    //系统发货单商品明细
                    List<ShiporderSku> shiporderSkuList = shiporderVO.getShiporderSkuList();
                    for (int shiporderSkuIndex = 0; shiporderSkuIndex < shiporderSkuList.size(); shiporderSkuIndex++) {
                        iResSku = 0;
                        ShiporderSku shiporderSku = shiporderSkuList.get(shiporderSkuIndex);
                        //系统发货单商品明细信息插入数据库
                        iResSku = shiporderService.insertSelectiveShiporderSku(shiporderSku);
                        if (iResSku > 0 && shiporderSku.getQty() != 0) {
                            //更新订单商品明细中的发货中数量
                            SysOrderGoods sysOrderGoods = new SysOrderGoods();
                            sysOrderGoods.setOrderGoodsId(shiporderSku.getOrderSkuId());
                            sysOrderGoods.setShippingQty(shiporderSku.getQty());
                            sysOrderDAO.updateByPrimaryKeySelectiveSysOrderGoods(sysOrderGoods);
                            //更新已分派数并记录库存变更日志
//调用OMS 库存Controller 更新已分派数,OMS调用方法中包含记录库存变更日志的方法
                            StockVO stockVO = new StockVO();
                            stockVO.setEntId(shiporderVO.getEntId());
                            stockVO.setStorId(shiporderVO.getStorId());
                            stockVO.setSkuId(shiporderSku.getSkuId());
                            stockVO.setAllotQty(shiporderSku.getQty());
                            stockVO.setSourceCode(shiporderVO.getShiporderCode());
                            stockVO.setTag("系统自动生成发货单");
                            // 请求地址
                            String requestUrl = omsUrl + "stock/updateStock.action";
                            // 请求参数拼接
                            String requestParams = JSON.toJSONString(stockVO);
                            // 请求数据
                            String resJson = HttpUtils.sendByPostJson(requestUrl, requestParams);


//                            //调用OMS 库存Controller 更新批次库存数或占用数,OMS调用方法中包含记录批次库存变更日志的方法
//                            BatchStockVO batchStockVO = new BatchStockVO();
//                            batchStockVO.setEntId(shiporderVO.getEntId());
//                            batchStockVO.setStorId(shiporderVO.getStorId());
//                            batchStockVO.setSkuId(shiporderSku.getSkuId());
//                            batchStockVO.setOccupyQty(shiporderSku.getQty());
//                            batchStockVO.setSourceCode(shiporderVO.getShiporderCode());
//                            batchStockVO.setTag("系统自动生成发货单");
//                            // 请求地址
//                            String requestUrlBatch = omsUrl + "stock/updateBatchStock.action";
//                            // 请求参数拼接
//                            String requestParamsBatch = JSON.toJSONString(batchStockVO);
//                            // 请求数据
//                            String resJsonBatch = HttpUtils.sendByPostJson(requestUrlBatch, requestParamsBatch);



                        }
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            iRes = 0;
            logUtil.error(new DBLog(shiporderVO.getShopId(), "系统订单自动审核分派", "跟踪日志", "发货单插入数据库阶段异常:" + ex.getMessage()));
        }
        return iRes;
    }

    /**
     * 校验订单商品是否全部都是虚拟商品
     *
     * @param strOrderId
     * @return 0:全是;1:部分是或全不是;-1:订单没有商品明细
     * @throws Exception
     */
    private int checkVirt(String strOrderId, Map<String, List<SysOrderGoods>> sysOrderGoodsMap) throws Exception {
        int iRes = 0;
        //判断订单商品明细是否全部为虚拟商品
        if (sysOrderGoodsMap != null && sysOrderGoodsMap.size() > 0) {
            List<SysOrderGoods> sysOrderGoodsList = sysOrderGoodsMap.get(strOrderId);
            if (sysOrderGoodsList != null && sysOrderGoodsList.size() > 0) {
                for (SysOrderGoods sysOrderGoods : sysOrderGoodsList) {
                    //判断订单明细中是否存在非虚拟商品
                    if ("n".equals(sysOrderGoods.getIsVirt())) {
                        iRes = 1;
                        break;
                    }
                }
            } else {
                iRes = -1;
            }
        } else {
            iRes = -1;
        }
        return iRes;
    }

}
